package com.zlm.unsafe;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: 郑
 * 不安全的集合  oncurrentModificationException 并发修改异常
 */
public class ListTest {
    public static void main(String[] args) {
        //并发下ArrayList不安全
        /**
         * 解决方案
         * 1 List<String> list1 = new Vector<>();
         * 2 List<String> list = Collections.synchronizedList(new ArrayList<>());
         * 3 List<String> list = new CopyOnWriteArrayList<>();
         * CopyOnWrite 写入时复制
         * 多线程调用时，list,读取时固定，写入覆盖
         * vector和copyOnWriteArrayList对比
         * vector效率低
         */
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0,4));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
}
